package com.km.wskj.itmonitor.pager.wq.forum;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.johnpersano.supertoasts.SuperActivityToast;
import com.github.johnpersano.supertoasts.SuperToast;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.adapter.GridImageAdapter;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.wq.forum.model.ForumParams;
import com.km.wskj.itmonitor.pager.wq.note.model.AddCallback;
import com.km.wskj.itmonitor.utils.FullyGridLayoutManager;
import com.km.wskj.itmonitor.utils.ListToStringUtils;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.LocalMediaLoader;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;
import com.zxl.zxlapplibrary.http.callback.StringCallback;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.view.ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author by Xianling.Zhou on 2017/3/30.
 */

//发帖页面
public class ForumSendActivity extends LActivity {

    private static final String TAG = "ForumSendActivity";

    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right_text)
    TextView toolBarRightText;
    @BindView(R.id.et_title)
    ClearEditText etTitle;
    @BindView(R.id.et_content)
    ClearEditText etContent;
    @BindView(R.id.recycler)
    RecyclerView recycler;

    private String columnId;
    private GridImageAdapter adapter;
    private int maxSelectNum = 9;// 图片最大可选数量
    private int cropW = 0;
    private int cropH = 0;
    private int compressW = 0;
    private int compressH = 0;
    private List<LocalMedia> selectMedia = new ArrayList<>();

    //保存笔记的方法
    private ArrayList<String> mImgIds;
    private String imgStr;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_forum);
        ButterKnife.bind(this);

        toolBarTitle.setText("发表主题");
        toolBarRightText.setText("发表");
        toolBarBack.setVisibility(View.VISIBLE);
        toolBarRightText.setVisibility(View.VISIBLE);

        if (getIntent().hasExtra("id"))
            columnId = getIntent().getStringExtra("id");

        initData();

    }

    private void initData() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(context, 4, GridLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(manager);
        adapter = new GridImageAdapter(context, onAddPicClickListener);
        adapter.setSelectMax(maxSelectNum);
        recycler.setAdapter(adapter);

        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                // 这里可预览图片
                PictureConfig.getPictureConfig().externalPicturePreview(context, position, selectMedia);
            }
        });
    }


    /**
     * 删除图片回调接口
     */

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick(int type, int position) {
            switch (type) {
                case 0:
                    // 进入相册
                    /**
                     * type --> 1图片 or 2视频
                     * copyMode -->裁剪比例，默认、1:1、3:4、3:2、16:9
                     * maxSelectNum --> 可选择图片的数量
                     * selectMode         --> 单选 or 多选
                     * isShow       --> 是否显示拍照选项 这里自动根据type 启动拍照或录视频
                     * isPreview    --> 是否打开预览选项
                     * isCrop       --> 是否打开剪切选项
                     * isPreviewVideo -->是否预览视频(播放) mode or 多选有效
                     * ThemeStyle -->主题颜色
                     * CheckedBoxDrawable -->图片勾选样式
                     * cropW-->裁剪宽度 值不能小于100  如果值大于图片原始宽高 将返回原图大小
                     * cropH-->裁剪高度 值不能小于100
                     * isCompress -->是否压缩图片
                     * setEnablePixelCompress 是否启用像素压缩
                     * setEnableQualityCompress 是否启用质量压缩
                     * setRecordVideoSecond 录视频的秒数，默认不限制
                     * setRecordVideoDefinition 视频清晰度  Constants.HIGH 清晰  Constants.ORDINARY 低质量
                     * setImageSpanCount -->每行显示个数
                     * setCheckNumMode 是否显示QQ选择风格(带数字效果)
                     * setPreviewColor 预览文字颜色
                     * setCompleteColor 完成文字颜色
                     * setPreviewBottomBgColor 预览界面底部背景色
                     * setBottomBgColor 选择图片页面底部背景色
                     * setCompressQuality 设置裁剪质量，默认无损裁剪
                     * setSelectMedia 已选择的图片
                     * setCompressFlag 1为系统自带压缩  2为第三方luban压缩
                     * 注意-->type为2时 设置isPreview or isCrop 无效
                     * 注意：Options可以为空，默认标准模式
                     */
                    FunctionConfig config = new FunctionConfig();
                    config.setType(LocalMediaLoader.TYPE_IMAGE);
                    config.setCopyMode(FunctionConfig.CROP_MODEL_DEFAULT);
                    config.setCompress(false);
                    config.setEnablePixelCompress(true);
                    config.setEnableQualityCompress(true);
                    config.setMaxSelectNum(maxSelectNum);
                    config.setSelectMode(FunctionConfig.MODE_MULTIPLE);
                    config.setShowCamera(true);
                    config.setEnablePreview(true);
                    config.setEnableCrop(false);
                    config.setPreviewVideo(true);//是否预览视频(播放)
                    config.setRecordVideoDefinition(FunctionConfig.HIGH);// 视频清晰度
                    config.setRecordVideoSecond(60);// 视频秒数
                    config.setCropW(cropW);
                    config.setCropH(cropH);
                    config.setCheckNumMode(false);//是否显示QQ选择风格(带数字效果)
                    config.setCompressQuality(100);
                    config.setImageSpanCount(4);
                    config.setSelectMedia(selectMedia);
                    config.setCompressFlag(1);//// 1 系统自带压缩 2 luban压缩
                    config.setCompressW(compressW);
                    config.setCompressH(compressH);


                    config.setThemeStyle(ContextCompat.getColor(context, R.color.colorWs_blue));
                    // 可以自定义底部 预览 完成 文字的颜色和背景色

                    config.setPreviewColor(ContextCompat.getColor(context, R.color.white));//底部预览文字颜色
                    config.setCompleteColor(ContextCompat.getColor(context, R.color.white));//底部完成文字颜色
                    config.setPreviewBottomBgColor(ContextCompat.getColor(context, R.color.colorWs_blue));//预览界面底部背景色
                    config.setBottomBgColor(ContextCompat.getColor(context, R.color.colorWs_blue));

                    // 先初始化参数配置，在启动相册
                    PictureConfig.init(config);
                    PictureConfig.getPictureConfig().openPhoto(context, resultCallback);

                    // 只拍照
                    //PictureConfig.getPictureConfig().startOpenCamera(mContext, resultCallback);
                    break;
                case 1:
                    // 删除图片
                    selectMedia.remove(position);
                    adapter.notifyItemRemoved(position);
                    break;
            }
        }
    };


    /**
     * 图片回调方法
     */
    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> resultList) {
            selectMedia = resultList;
            Log.i("callBack_result", selectMedia.size() + "");

            if (selectMedia != null) {
                adapter.setList(selectMedia);
                adapter.notifyDataSetChanged();
            }
        }
    };

    /**
     * 判断 一个字段的值否为空
     *
     * @param s
     * @return
     * @author Michael.Zhang 2013-9-7 下午4:39:00
     */

    public boolean isNull(String s) {
        if (null == s || s.equals("") || s.equalsIgnoreCase("null")) {
            return true;
        }

        return false;
    }

    @OnClick({R.id.tool_bar_back, R.id.tool_bar_right_text})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tool_bar_right_text:

                mImgIds = new ArrayList<>();

                final String title = etTitle.getText().toString();
                final String content = etContent.getText().toString();

                if (title.equals("")) {
                    normalToasty("请输入标题");
                    return;
                }

                if (content.equals("")) {
                    normalToasty("请输入正文");
                    return;
                }

                final SuperActivityToast superActivityToast = new SuperActivityToast(context, SuperToast.Type.PROGRESS);
                superActivityToast.setIndeterminate(true);
                superActivityToast.setText("请稍后...");
                superActivityToast.setProgressIndeterminate(true);
                superActivityToast.show();

                //有图片的情况
                if (selectMedia.size() > 0) {
                    for (int i = 0; i < selectMedia.size(); i++) {
                        pdc.uploadPic(HTTP_TASK_TAG, selectMedia.get(i), new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int i) {
                                LogUtils.e(TAG + e.getLocalizedMessage());
                            }

                            @Override
                            public void onResponse(String s, int i) {
                                JSONObject json = JSON.parseObject(s);
                                String attach_id = json.getString("attach_id");
                                mImgIds.add(attach_id);

                                //图片都上传完成以后执行操作
                                if (mImgIds.size() == selectMedia.size()) {
                                    imgStr = ListToStringUtils.listToString(mImgIds, ",");
                                    ForumParams params = new ForumParams();
                                    params.columnId = columnId;
                                    params.title = title;
                                    params.content = content;
                                    params.imgIds = imgStr;
                                    params.userId = pdc.mCurrentUser.userId;

                                    //发帖
                                    pdc.sendForum(HTTP_TASK_TAG, params, new ZxlGenericsCallback<AddCallback>() {
                                        @Override
                                        public void onError(Call call, Exception e, int i) {
                                            LogUtils.e(TAG, e);
                                        }

                                        @Override
                                        public void onResponse(AddCallback addCallback, int i) {
                                            superActivityToast.dismiss();
                                            normalToasty(addCallback.msg);

                                            new Handler().postDelayed(new Runnable() {
                                                @Override
                                                public void run() {
                                                    startActivity(new Intent(context, ForumActivity.class));
                                                    finish();
                                                }

                                            }, 500);
                                        }
                                    });
                                }
                            }
                        });
                    }

                    //没图片的情况
                } else {
                    ForumParams params = new ForumParams();
                    params.columnId = columnId;
                    params.title = title;
                    params.content = content;
                    params.userId = pdc.mCurrentUser.userId;

                    //发帖
                    pdc.sendForum(HTTP_TASK_TAG, params, new ZxlGenericsCallback<AddCallback>() {
                        @Override
                        public void onError(Call call, Exception e, int i) {
                            LogUtils.e(TAG, e);
                        }

                        @Override
                        public void onResponse(AddCallback addCallback, int i) {
                            superActivityToast.dismiss();
                            normalToasty(addCallback.msg);

                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    startActivity(new Intent(context, ForumActivity.class));
                                    finish();
                                }

                            }, 500);
                        }
                    });

                }

                break;
        }
    }
}
